import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/http/request/leaderboard_week_rank_request.dart';
import 'package:elephant_fish/http/request/leaderboard_year_rank_request.dart';
import 'package:elephant_fish/model/rank_entity.dart';
import 'package:elephant_fish/model/rank_year_entity.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:elephant_fish/widget/rank_card_list.dart';
import 'package:elephant_fish/widget/rank_year_card_list.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'login_page.dart';

class IndexRankWeekendPage extends StatefulWidget {
  final String categoryName;

  const IndexRankWeekendPage({Key key, this.categoryName,}) : super(key: key);

  @override
  _IndexRankWeekendPageState createState() => _IndexRankWeekendPageState();
}

class _IndexRankWeekendPageState extends State<IndexRankWeekendPage> {
  List<RankYearEntity> rankYearEntities;
  List<RankEntity> rankEntities;
  int pageIndex = 1;
  bool _loading = false;

  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _scrollController.addListener(() {
      var dis = _scrollController.position.maxScrollExtent -
          _scrollController.position.pixels;
      //当距离底部不足300时加载更多
      if (dis < 300 && !_loading) {
        if(widget.categoryName == '周&星榜'){
          getWeekendRankList(loadMore: true);
        }else{
          getYearRankList(loadMore: true);
        }

      }
    });
    if(widget.categoryName == '周&星榜'){
      getWeekendRankList();
    }else{
      getYearRankList();
    }
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xff140c3d),
      body:
      widget.categoryName == '周&星榜' ?
      ListView.builder(
              itemCount: rankEntities == null ? 0 : rankEntities.length,
              itemBuilder: (context,index){
            return RankCardList(rankEntity: rankEntities[index],);
          }
      ) :
      ListView.builder(
          itemCount: rankEntities == null ? 0 : rankEntities.length,
          itemBuilder: (context,index){
            return RankYearCardList(rankYearEntity: rankYearEntities[index],);
          }
      )
      ,
    );
  }

  getWeekendRankList({loadMore = false}) async {
    _loading = true;
    if (!loadMore) {
      pageIndex = 1;
    }
    var currentIndex = pageIndex + (loadMore ? 1 : 0);
    print('loading:currentIndex:$currentIndex');
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = LeaderBoardWeekRankRequest();
    request.add('type', 2).add('page', pageIndex).add('limit', 6).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    } else if (result['code'] == 0) {
      List<Map<String, dynamic>> listMap =
      new List<Map<String, dynamic>>.from(result['data']['data']);
      List<RankEntity> list = List();
      for (int i = 0; i < listMap.length; i++) {
        list.add(RankEntity.fromJson(listMap[i]));
      }
      setState(() {
        if (loadMore) {
          if (list.isNotEmpty) {
            //合成一个新数组
            rankEntities = [...rankEntities, ...list];
            pageIndex++;
          }
        } else {
          rankEntities = list;
        }
      });
      Future.delayed(Duration(milliseconds: 1000), () {
        _loading = false;
      });
    }
  }

  getYearRankList({loadMore = false}) async {
    _loading = true;
    if (!loadMore) {
      pageIndex = 1;
    }
    var currentIndex = pageIndex + (loadMore ? 1 : 0);
    print('loading:currentIndex:$currentIndex');
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = LeaderBoardYearRankRequest();
    request.add('type', 2).add('page', pageIndex).add('limit', 6).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    } else if (result['code'] == 0) {
      List<Map<String, dynamic>> listMap =
      new List<Map<String, dynamic>>.from(result['data']['data']);
      List<RankYearEntity> list = List();
      for (int i = 0; i < listMap.length; i++) {
        list.add(RankYearEntity.fromJson(listMap[i]));
      }
      setState(() {
        if (loadMore) {
          if (list.isNotEmpty) {
            //合成一个新数组
            rankYearEntities = [...rankYearEntities, ...list];
            pageIndex++;
          }
        } else {
          rankYearEntities = list;
        }
      });
      Future.delayed(Duration(milliseconds: 1000), () {
        _loading = false;
      });
    }
  }
}
